/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.judge;

import beans.Judge;
import java.beans.IntrospectionException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;
import xml.beer.BeerWriter;

/**
 *
 * @author heinen
 */
public class JudgeWriter {

    BeanWriter writer;
    FileOutputStream fos;
    StringWriter content;

    public JudgeWriter() {
    }

    public boolean print(Judge judge) {
        JudgeReader judgeReader = new JudgeReader();
        List<Judge> allJudges = judgeReader.getAllJudges();
        if (allJudges == null || allJudges.size() == 0) {
            allJudges = new ArrayList<>();
        }
        allJudges.add(judge);
        return printInXML(allJudges);
    }

    public boolean printInXML(List<Judge> judges) {
        content = new StringWriter();
        content.write("<?xml version='1.0'?>\r\n");
        content.write("<judges>\r\n");
        try {
            writer = new BeanWriter(content);
            writer.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
            writer.enablePrettyPrint();
            writer.getBindingConfiguration().setMapIDs(false);
            writer.start();
            for (Judge j : judges) {
                writer.write(j);
            }
            writer.end();
            content.write("</judges>");
            System.out.println(content);
            File f = new File("src\\xml\\judge\\judges.xml");
            if (!f.exists()) {
                f.createNewFile();
            }
            PrintWriter out = new PrintWriter(f);
            out.print(content);
            out.flush();
            return true;
        } catch (IOException ex) {
            writer = null;
            ex.printStackTrace();
        } catch (SAXException ex) {
            Logger.getLogger(BeerWriter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IntrospectionException ex) {
            Logger.getLogger(BeerWriter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    public boolean remove(Judge j) {
        JudgeReader judgeReader = new JudgeReader();
        List<Judge> allJudges = judgeReader.getAllJudges();
        if (allJudges.contains(j)) {
            allJudges.remove(j);
            return printAllJudges(allJudges);
        } else {
            return false;
        }
    }

    private boolean printAllJudges(List<Judge> allJudges) {
        return printInXML(allJudges);
    }
}
